
class Sha256:
    block_size_in_byte = 64  # 512 bits
    last_block_size_limit = 56  # 440 bits
    data_length_size_in_byte = 8  # 64 bits
    kvalue = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
              0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
              0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
              0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
              0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
              0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
              0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
              0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]

    def __init__(self):
        self.H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
        # 上次add_data时残留，不足block_size_in_byte的剩余数据
        self.last_data = None
        self.count = 0
        self.data_total_size_in_bit = 0

    def add_data(self, data):
        if not data:
            return

        blocks = self.split_data(data)
        if not blocks:
            return

        for block in blocks:
            self.process_block(block)

    def split_data(self, original_data):
        """
        将original_data分割成64-byte大小的block，最后一个block如果小于64-byte，则将其存在last_block中
        :param data:
        :return:
        """
        if not original_data:
            return None
        data = bytearray()

        # 如果last_data中有数据，那么
        if self.last_data:
            data += self.last_data
            self.last_data = None
        data += original_data
        length = len(data)
        self.data_total_size_in_bit += len(original_data) * 8
        full_block_count = int(length / self.block_size_in_byte)
        blocks = []
        for i in range(full_block_count):
            block = data[i * self.block_size_in_byte: (i + 1) * Sha256.block_size_in_byte]
            blocks.append(block)
        surplus_data_size = length % self.block_size_in_byte
        if surplus_data_size > 0:
            self.last_data = data[full_block_count * self.block_size_in_byte:]
        return blocks

    def process_block(self, block):
        """
        计算一个block的hash值
        :param block:
        :return:
        """
        if not block:
            return
        M = Sha256.split_block(block)
        # print("process block %d" % i)
        # print(M)
        a = self.H[0]
        b = self.H[1]
        c = self.H[2]
        d = self.H[3]
        e = self.H[4]
        f = self.H[5]
        g = self.H[6]
        h = self.H[7]
        for j in range(64):
            t1 = (h + Sha256.SIGMA1(e) + Sha256.Ch(e, f, g) + Sha256.K(j) + Sha256.W(M, j)) & 0xFFFFFFFF
            t2 = (Sha256.SIGMA0(a) + Sha256.Maj(a, b, c)) & 0xFFFFFFFF
            h = g
            g = f
            f = e
            e = (d + t1) & 0xFFFFFFFF
            d = c
            c = b
            b = a
            a = (t1 + t2) & 0xFFFFFFFF
        self.H[0] = (self.H[0] + a) & 0xFFFFFFFF
        self.H[1] = (self.H[1] + b) & 0xFFFFFFFF
        self.H[2] = (self.H[2] + c) & 0xFFFFFFFF
        self.H[3] = (self.H[3] + d) & 0xFFFFFFFF
        self.H[4] = (self.H[4] + e) & 0xFFFFFFFF
        self.H[5] = (self.H[5] + f) & 0xFFFFFFFF
        self.H[6] = (self.H[6] + g) & 0xFFFFFFFF
        self.H[7] = (self.H[7] + h) & 0xFFFFFFFF

    def process_last_data(self):
        """
        处理最后的不足64-byte大小的数据
        :return:
        """
        if not self.last_data:
            self.last_data = bytearray()
        length = len(self.last_data)
        # step 1: 填充data，至64字节对齐，最后一个block格式如下：
        """
        ++++++++++++++++++++++++++++++++
        |   data  |0x80| zeros |8 bytes|
        ++++++++++++++++++++++++++++++++
        """
        block_count = 1
        if length < Sha256.last_block_size_limit:
            # 一个block就可以满足上面格式
            paddingSizeInByte = Sha256.last_block_size_limit - length
        else:
            # 一个blockblock满足不了上面格式，需要创造一个block继续填充，以满足上述格式
            paddingSizeInByte = Sha256.block_size_in_byte - length + Sha256.last_block_size_limit
            block_count += 1
        # print("original data: >>>>>>>>")
        # printData(data)
        # print("length = " + str(length) + ", mod = " + str(modLength) + ", padding dize = " + str(paddingSizeInByte))
        # sub step 1: append 0xA0
        self.last_data.append(0x80)
        # sub step 2: append zeros
        paddingSizeInByte -= 1
        zeros = b'\0' * paddingSizeInByte
        self.last_data += zeros
        # sub step 3: append length of the data
        and_num = 0xFF00000000000000
        for i in range(8):
            # print(">>>>>>>>>>>> " + str(i))
            current_and_num = and_num >> (i * 8)
            temp = current_and_num & self.data_total_size_in_bit
            result = temp >> ((7 - i) * 8)
            # print("andNum = %x, length = %x, temp = %x, result = %x" % (currentAndNum, length, temp, result))
            self.last_data.append(result)
        # print("Final data: >>>>>>>>")
        # printData(data)

        for i in range(block_count):
            block = self.last_data[i * Sha256.block_size_in_byte: (i + 1) * Sha256.block_size_in_byte]
            self.process_block(block)


    def get_value(self):
        self.process_last_data()
        result = format("%08x%08x%08x%08x%08x%08x%08x%08x" % (
            self.H[0], self.H[1], self.H[2], self.H[3], self.H[4], self.H[5], self.H[6], self.H[7]))
        return result

    @staticmethod
    def split_block(block):
        """
        将一个block转化成为16个32位整型数
        :param block:
        :return:
        """
        if not block:
            raise RuntimeError("block is null")
        length = len(block)
        if length != 64:
            raise RuntimeError("block size is not 64 bytes")
        slice_count = int(length / 4)
        slices = []
        for i in range(slice_count):
            start = i * 4
            end = (i + 1) * 4
            temp = block[start:end]
            sli = (temp[0] << 24) | (temp[1] << 16) | (temp[2] << 8) | temp[3]
            slices.append(sli)
            # print("0x%x" % sli)
        return slices

    # right rotation
    @staticmethod
    def S(x, n):
        if n < 0:
            raise RuntimeError("right rotation %d is negative" % n)
        n = n % 32
        if n == 0:
            return x
        one_bits = 0
        for i in range(n):
            one_bits = one_bits | (1 << i)
        return ((x & one_bits) << (32 - n)) | (x >> n)

    # right rotation
    @staticmethod
    def S(x, n):
        if n < 0:
            raise RuntimeError("right rotation %d is negative" % n)
        n = n % 32
        if n == 0:
            return x
        one_bits = 0
        for i in range(n):
            one_bits = one_bits | (1 << i)
        return ((x & one_bits) << (32 - n)) | (x >> n)

    # right shift
    @staticmethod
    def R(x, n):
        if n < 0:
            raise RuntimeError("right rotation %d is negative" % n)
        return x >> n

    @staticmethod
    def Ch(x, y, z):
        return ((x & y) ^ ((~x) & z)) & 0xFFFFFFFF

    @staticmethod
    def Maj(x, y, z):
        return ((x & y) ^ (x & z) ^ (y & z)) & 0xFFFFFFFF

    @staticmethod
    def SIGMA0(x):
        return (Sha256.S(x, 2) ^ Sha256.S(x, 13) ^ Sha256.S(x, 22)) & 0xFFFFFFFF

    @staticmethod
    def SIGMA1(x):
        return (Sha256.S(x, 6) ^ Sha256.S(x, 11) ^ Sha256.S(x, 25)) & 0xFFFFFFFF

    @staticmethod
    def sigma0(x):
        return (Sha256.S(x, 7) ^ Sha256.S(x, 18) ^ Sha256.R(x, 3)) & 0xFFFFFFFF

    @staticmethod
    def sigma1(x):
        return (Sha256.S(x, 17) ^ Sha256.S(x, 19) ^ Sha256.R(x, 10)) & 0xFFFFFFFF

    @staticmethod
    def W(slices, i):
        if not slices:
            raise RuntimeError("W: slices is null")
        if i < 0 or i > 63:
            raise RuntimeError("W: index %d is illegal" % i)
        length = len(slices)
        if length != 16:
            raise RuntimeError("W: slices sum %d is not equal to 16" % length)
        if i < 16:
            return slices[i]
        else:
            return (Sha256.sigma1(Sha256.W(slices, i - 2)) + Sha256.W(slices, i - 7) + Sha256.sigma0(
                Sha256.W(slices, i - 15)) + Sha256.W(slices, i - 16)) & 0xFFFFFFFF

    @staticmethod
    def K(i):
        return Sha256.kvalue[i]


if __name__ == "__main__":
    # data = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012"
    # data = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123"
    samples = {"abc": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
               "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq": "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"}
    data = list(samples.keys())[1]
    print("Calculate hash value of string: " + data)
    expected = samples[data]
    sha = Sha256()
    sha.add_data(bytearray(data, 'utf-8'))
    hashValue = sha.get_value()
    if expected == hashValue:
        print("Got correct hash value: " + expected)
    else:
        print("Expected hash value:\n" + expected + "\nbut actual hash value:\n" + hashValue)
